package org.springboot3.project.demoapi.controller;

import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ConsumerConfig;
import org.apache.dubbo.config.MethodConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.rpc.service.GenericService;
import org.springboot3.project.demoapi.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * todo
 *
 * @author weiwei
 * @since 2024/6/11 11:38
 */
@RestController
public class TestController {

    @Autowired
    private TestService testService;

    private static String DUBBO_DEFAULT_APPLICATION_NAME = "shenyu_proxy";

    @GetMapping("/test")
    public String test(){
//        String s = testService.test(key);

        ApplicationConfig applicationConfig = new ApplicationConfig(DUBBO_DEFAULT_APPLICATION_NAME);
        applicationConfig.setQosEnable(false);
        applicationConfig.setRegisterConsumer(true);

        RegistryConfig registryConfigItem = new RegistryConfig();
        registryConfigItem.setId(DUBBO_DEFAULT_APPLICATION_NAME);
        registryConfigItem.setRegister(false);
//        registryConfig.setAddress("nacos://172.16.22.22:8848?namespace=local_weiwei&username=nacos&password=expos_nacos");
        registryConfigItem.setProtocol("nacos");
        registryConfigItem.setAddress("172.16.22.22:8848?namespace=local_weiwei");
        registryConfigItem.setUsername("nacos");
        registryConfigItem.setPassword("expos_nacos");

        ConsumerConfig consumerConfig = new ConsumerConfig();
        consumerConfig.refresh();
        consumerConfig.setRetries(0);
        consumerConfig.setTimeout(3000);

        ReferenceConfig<GenericService> reference = new ReferenceConfig<>();
        reference.setGeneric("true");
//        reference.setAsync(true);

        reference.setApplication(applicationConfig);
        reference.setRegistry(registryConfigItem);
        reference.setConsumer(consumerConfig);

        reference.setInterface("org.springboot3.project.demoapi.DemoService");
        reference.setVersion("1.0");
        // default protocol is dubbo
//        reference.setProtocol(CommonConstants.DUBBO);
        reference.setCheck(false);


        Map<String, String> parameters = new HashMap<>(2);
        parameters.put("dispatcher", "direct");
        reference.setParameters(parameters);

        GenericService genericService = reference.get();
        Object result = genericService.$invoke("sayHello", new String[] { "java.lang.String"}, new String[] { "World" });
        return result.toString();
    }

}
